package com.symone.webcms.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.symone.webcms.common.Constants;
import com.symone.webcms.mapper.UserMapper;
import com.symone.webcms.model.Role;
import com.symone.webcms.model.User;
import com.symone.webcms.model.vo.UserInfoVO;
import com.symone.webcms.model.vo.UserVO;
import com.symone.webcms.service.UserService;
import com.symone.webcms.util.CommonUtil;
import com.xiaoleilu.hutool.json.JSONObject;
import com.xiaoleilu.hutool.lang.Validator;
import com.xiaoleilu.hutool.util.RandomUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 系统用户表 服务实现类
 * </p>
 *
 * @author ArcherChu
 * @since 2018-10-30
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean insert(User user) {
        return baseMapper.insert(user) > 0;
    }

    @Override
    public UserVO findUserByName(String name) {
        UserVO user ;
        if(Validator.isEmail(name)){
            user = baseMapper.findUserByEmail(name);
        }else if(Validator.isMobile(name)){
            user = baseMapper.findUserByMobile(name);
        }else{
            user = baseMapper.findUserByUserName(name);
        }
        return user;
    }

    /**
     * 保存用户验证码，和randomStr绑定
     *
     * @param randomStr 客户端生成
     * @param imageCode 验证码信息
    */
    @Override
    public void saveImageCode(String randomStr, String imageCode) {
        redisTemplate.opsForValue().set(Constants.DEFAULT_CODE_KEY + randomStr, imageCode, Constants.DEFAULT_IMAGE_EXPIRE, TimeUnit.SECONDS);
    }

    @Override
    public Boolean sendSmsCode(String mobile) {
        Object tempCode = redisTemplate.opsForValue().get(Constants.DEFAULT_CODE_KEY + mobile);
        if (tempCode != null) {
            log.error("用户:{}验证码未失效{}", mobile, tempCode);
            return false;
            //return new ResultMessage<>(false, "验证码未失效，请失效后再次申请");
        }

        UserVO userVO = baseMapper.findUserByMobile(mobile);
        if(userVO == null) {
            log.error("根据用户手机号{}查询用户为空", mobile);
            return false;
            //return new ResultMessage<>(false, "手机号不存在");
        }

        String code = RandomUtil.randomNumbers(4);
        JSONObject contextJson = new JSONObject();
        contextJson.put("code", code);
        contextJson.put("product", "Symone4Cloud");
        log.info("短信发送请求消息中心 -> 手机号:{} -> 验证码：{}", mobile, code);

        //TODO:

        redisTemplate.opsForValue().set(Constants.DEFAULT_CODE_KEY + mobile, code, Constants.DEFAULT_IMAGE_EXPIRE, TimeUnit.SECONDS);
        return true;
        //return new ResultMessage<>(true);
    }

    @Override
    public boolean changePassword(long id,String userName,String password) {
        User user = baseMapper.selectById(id);
        user.setUserName(userName);
        user.setPassword(CommonUtil.encodePassword(password));
        return baseMapper.updateById(user) > 0;
    }

    @Override
    public Page<UserInfoVO> getUserListByParameters(Page<UserInfoVO> page, String userName, String mobile, String email, String roleId, Integer state) {
        List<UserInfoVO> result =  baseMapper.selectUserListByParameters(page,userName,mobile,email,roleId,state);
        page.setRecords(result);
        return page;
    }

    @Override
    public void updateUser(User user) {
        String password = "";
        if(StrUtil.isNotEmpty(user.getPassword())) {
            password = CommonUtil.encodePassword(user.getPassword());
        }
        baseMapper.updateUser(user.getId(),user.getUserName(),user.getMobile(),user.getEmail(),user.getNickName(),password,user.getAvatar(),user.getRoleId(),user.getState());
    }

    @Override
    public int delete(long id) {
        return baseMapper.deleteById(id);
    }

    @Override
    public int clear() {
        return baseMapper.delete(new EntityWrapper<>());
    }
}
